package com.xdap.fsapproval.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xdap.common.config.LocalValue;
import com.xdap.fsapproval.service.AsagelFeishuService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @BelongsProject：IntelliJ IDEA
 * @BelongsPackage：com.xdap.cyms.orgUser.service.impl
 * @Author：fei
 * @CreateTime：2022-08-29 17:14
 * @Description: 飞书服务实现
 * @Version：1.0
 */
@Service
@Slf4j
@LocalValue
public class AsagelFeishuServiceImpl implements AsagelFeishuService {

    private static final String feishuRedisKey = "feishuTokenAdisso";
    private static final String appId = "app_id";
    private static final String appSecret = "app_secret";
    private static final String appAccessToken = "app_access_token";

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RestTemplate restTemplate;

    @LocalValue("${feishu.application.client_id}")
    private String feishuClientId;

    @LocalValue("${feishu.application.client_secret}")
    private String feishuClientSecret;

    @LocalValue(value = "${feishu.app.access.token.url}")
    private String appAccessTokenUrl;


    @Override
    public String getToken() {

        String feishuToken = redisTemplate.opsForValue().get(feishuRedisKey);
        if (StringUtils.isNotBlank(feishuToken)) {
            log.info("redis获取到的toke" + feishuToken);
            return feishuToken;
        } else {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put(appId, feishuClientId);
            jsonObject.put(appSecret, feishuClientSecret);
            HttpHeaders httpHeaders = new HttpHeaders();
            // 设置请求类型
            httpHeaders.setContentType(MediaType.APPLICATION_JSON);
            // 封装参数和头信息
            HttpEntity<JSONObject> httpEntity = new HttpEntity(jsonObject, httpHeaders);
            ResponseEntity<String> mapResponseEntity = restTemplate.postForEntity(appAccessTokenUrl, httpEntity, String.class);
            log.info(mapResponseEntity.getBody());
            HashMap hashMap = JSON.parseObject(mapResponseEntity.getBody(), HashMap.class);
            redisTemplate.opsForValue().set(feishuRedisKey, (String) hashMap.get(appAccessToken), 30, TimeUnit.MINUTES);
            return (String) hashMap.get(appAccessToken);
        }
    }
}
